package com.mjkj.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mjkj.demo.core.exception.ErrorCode;
import com.mjkj.demo.core.exception.ServiceException;
import com.mjkj.demo.mapper.UserMapper;
import com.mjkj.demo.model.LoginUser;
import com.mjkj.demo.model.entity.User;
import com.mjkj.demo.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author keeng
 * @since 2025/9/10
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Resource
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
		if (user == null) {
			throw new ServiceException(new ErrorCode(201, "用户不存在"));
		}

		return LoginUser.builder()
				.user(user)
				.build();
	}
}
